package com.yonyou.portcity.config;

import com.yonyou.portcity.utils.AuthUtil;
import com.yonyou.portcity.utils.RedisTokenHelper;
import com.yonyou.portcity.utils.WxUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.SQLException;


/**
 * Created by WangCan on 2018/6/1.
 * 定时刷新获取token信息，保存到redis
 */
@Component
public class Scheduler {

    private static final Logger logger = LoggerFactory.getLogger(Scheduler.class);

    public static String JSAPIURL = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=";

    @Resource
    private RedisTokenHelper redisTokenHelper;
    /**
     * 定时获取access_token
     * @throws SQLException
     */
    @Scheduled(initialDelay = 1000,fixedDelay=6600000)
    public void getAccessToken() throws IOException {
        //获取access_token
        logger.info("==============开始获取access_token===============");
        String tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" +
                "corpid=" + AuthUtil.APPID +
                "&corpsecret="+ AuthUtil.APPSECRET;
        JSONObject tokenObject = AuthUtil.doGetJson(tokenUrl);
        System.out.println("tokenObject="+tokenObject.toString());
        String access_token = tokenObject.getString("access_token");

        logger.info("==============结束获取access_token==============="+access_token);

        logger.info("==============开始写入access_token===============");
        System.out.println(access_token);
        redisTokenHelper.saveObject("global_token", access_token);
        logger.info("==============写入access_token成功===============");

        String url = JSAPIURL + access_token;
        JSONObject result = WxUtil.httpRequest(url,"GET",null);
        String ticket = (String) result.get("ticket");
        logger.info("==============写入ticket成功==============="+ticket);
        redisTokenHelper.saveObject("ticket", ticket);

    }
}
